package com.example.lemis.common.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;

public class AtLeastOneNotBlankValidator implements ConstraintValidator<AtLeastOneNotBlank, Object> {

    private String[] fields;

    @Override
    public void initialize(AtLeastOneNotBlank anno) {
        this.fields = anno.fields();   // 取注解里的字段名
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext ctx) {
        if (value == null) {
            return true;               // 交给 @NotNull 去管
        }

        var bean = new BeanWrapperImpl(value);

        for (String field : fields) {
            Object v = bean.getPropertyValue(field);

            // 字符串：去掉空白后还有内容
            if (v instanceof CharSequence cs && StringUtils.hasText(cs)) {
                return true;
            }
            // 其他类型：只要非 null
            if (v != null && !(v instanceof CharSequence)) {
                return true;
            }
        }
        return false;                  // 全部为空 => 不合法
    }
}
